import { OrganizationInfo } from 'admin/schema/Organization';

/**
 * 在开发中，时常会遇到需要设置组织机构的初始值，由于使用的级联选择器，传入值需要一个完整的id路径
 * 思路：首先将组织结构的数据结构扁平化，然后递归获取父级节点的id
 */
export const getOrganizationPath = (item: OrganizationInfo[], targetId: number): number[] => {
  if (targetId == null) {
    return [];
  }

  const arr: any[] = [];
  const deepFind = (item: OrganizationInfo) => {
    arr.push({
      id: item.organizationId,
      name: item.organizationName,
      idParent: item.idParent !== -1 ? item.idParent : null,
    });
    if (item.subOrganizations) {
      item.subOrganizations.forEach(son => {
        deepFind(son);
      });
    }
  };
  const defaultVal: number[] = [];
  const find = (target: any) => {
    defaultVal.push(target.id);
    if (target.idParent !== null) {
      const aim = arr.find(item => item.id === target.idParent);
      find(aim);
    }
  };
  item.forEach(item => {
    deepFind(item);
  });
  find(arr.find(item => item.id === targetId));
  return defaultVal.reverse();
};

export const getOrganizationFullPath = (
  item: OrganizationInfo[],
  targetId: number
): OrganizationInfo[] => {
  if (targetId == null) {
    return [];
  }

  const arr: any[] = [];
  const deepFind = (item: OrganizationInfo) => {
    arr.push({
      id: item.organizationId,
      name: item.organizationName,
      idParent: item.idParent !== -1 ? item.idParent : null,
      companyId: item.companyId,
    });
    if (item.subOrganizations) {
      item.subOrganizations.forEach(son => {
        deepFind(son);
      });
    }
  };
  const defaultVal: OrganizationInfo[] = [];
  const find = (target: any) => {
    defaultVal.push(target);
    if (target.idParent !== null) {
      const aim = arr.find(item => item.id === target.idParent);
      find(aim);
    }
  };
  item.forEach(item => {
    deepFind(item);
  });
  find(arr.find(item => item.id === targetId));
  return defaultVal.reverse();
};
